package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketAddress;

import common.RequestMsg;
import common.UpdateMsg;

public class ServerMulticastThread implements Runnable{

	private boolean isActive;
	private ServerImpl server;

	public ServerMulticastThread(ServerImpl server){

		isActive = true;
		this.server = server;

	}
	@Override
	public void run() {

		try {

			MulticastSocket socket = new MulticastSocket(4446);
			InetAddress address = InetAddress.getByName("239.255.0.1");
			InetSocketAddress socketAddress = new InetSocketAddress("239.255.0.1", 4446);
			NetworkInterface networkInterface = NetworkInterface.getByInetAddress(address);

			socket.joinGroup(socketAddress, networkInterface);
			

			while(isActive){

				byte[] buf = new byte[256];
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				String receivedPacketString = new String(packet.getData(), 0, packet.getLength());
				
				String[] parts = receivedPacketString.split(":");
				
				int sequenceNum = Integer.valueOf(parts[0]).intValue();
				int msgId = Integer.valueOf(parts[1]).intValue();
				int dataId = Integer.valueOf(parts[2]).intValue();
				int newValue = Integer.valueOf(parts[3]).intValue();
				
				RequestMsg requestMsg = new RequestMsg(msgId,dataId,newValue);
				UpdateMsg updateMsg = new UpdateMsg(sequenceNum,requestMsg);
				server.update(updateMsg);

			}

			socket.close();

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}


	}


	public void stopListening(){

		isActive = false;
	}


}